import roleHarvester from "./mount/role/harvester";
import roleUpgrader from "./mount/role/upgrader";
import roleBuilder from "./mount/role/builder";
// import {structureTower} from "./mount/structure/structureIndex"
module.exports.loop = function () {
    for (var name in Memory.creeps) {
        // 释放内存
        if (!Game.creeps[name]) {
            delete Memory.creeps[name];
            console.log("Clearing non-existing creep memory:", name);
        }
    }

    var harvester = _.filter(
        Game.creeps,
        (creep) => creep.memory.role == "harvester"
    ); //这里用的是lodash语法，筛选出执行harvester逻辑的爬爬
    var upgrader = _.filter(
        Game.creeps,
        (creep) => creep.memory.role == "upgrader"
    ); //这里用的是lodash语法，筛选出执行upgrader逻辑的爬爬
    var builder = _.filter(
        Game.creeps,
        (creep) => creep.memory.role == "builder"
    ); //这里用的是lodash语法，筛选出执行builder逻辑的爬爬

    // harvester少于2的时候生产harvester
    if (harvester.length < 2) {
        var newName = "Harvester" + Game.time; //爬爬命名
        console.log("Spawning new harvester: " + newName); //控制台输出
        Game.spawns["Spawn1"].spawnCreep(
            [WORK, CARRY, MOVE],
            newName, //定义爬爬的体型
            { memory: { role: "harvester" } }
        ); // 指定role属性
    }
    if (harvester.length == 2 && upgrader.length < 2) {
        var newName = "Upgrader" + Game.time; //爬爬命名
        console.log("Spawning new upgrader: " + newName); //控制台输出
        Game.spawns["Spawn1"].spawnCreep(
            [WORK, CARRY, MOVE],
            newName, //定义爬爬的体型
            { memory: { role: "upgrader" } }
        ); // 指定role属性
    } if (upgrader.length < 2 && builder.length < 1) {
        var newName = "Builder" + Game.time; //爬爬命名
        console.log("Spawning new builder: " + newName); //控制台输出
        Game.spawns["Spawn1"].spawnCreep(
            [WORK, CARRY, MOVE],
            newName, //定义爬爬的体型
            { memory: { role: "builder" } }
        ); // 指定role属性
    }

    if (Game.spawns["Spawn1"].spawning) {
        // 孵化过程可视化
        var spawningCreep = Game.creeps[Game.spawns["Spawn1"].spawning.name];
        Game.spawns["Spawn1"].room.visual.text(
            "🛠️" + spawningCreep.memory.role,
            Game.spawns["Spawn1"].pos.x + 1,
            Game.spawns["Spawn1"].pos.y,
            { align: "left", opacity: 0.8 }
        );
    }

    for (var name in Game.creeps) {
        var creep = Game.creeps[name];
        if (creep.memory.role == "harvester") {
            roleHarvester.run(creep);
        }
        if (creep.memory.role == "upgrader") {
            roleUpgrader.run(creep);
        }
        if (creep.memory.role == "builder") {
            roleBuilder.run(creep);
        }
    }
};
